<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
    <script type="text/javascript">
        var context_path = '<%=path%>';
    </script>
    <style type="text/css">
        #shevle_list_container {
            width: 100%;
            height: 100%;
            position:absolute;
        }

        #shevle_list_areaTreeDiv {
            width: 200px;
            height: 100%;
            border-right: solid 1px #cdcfd0;
            float: left;
            padding-left: 5px;
            padding-top: 10px;
            display: inline;
        }

        #shevle_list_grid-div {
            width: calc(100% - 220px);
            height: 100%;
            float: left;
            padding: 5px 0 5px 5px;
        }
    </style>
<!-- 货架管理页面 -->
<div id="shevle_list_container" >
    <div id="shevle_list_areaTreeDiv" class="ztree" style="overflow-y:auto;"></div>
	<form id="shevle_list_hiddenForm" action="<%=path%>/wmsshevle/toExcel" method="POST" style="display: none;">
		<input type="text" id="shevle_list_ids" name="ids" value=""/>
	</form>
    <div id="shevle_list_grid-div">
        <!-- 隐藏区域：存放查询条件 -->
        <form id="shevle_list_hiddenQueryForm" style="display:none;">
            <input id="shevle_list_shevelNo" name="shevelNo" value="" />
            <input id="shevle_list_shevelName" name="shevelName" value="" />
            <input id="shevle_list_dCode" name="dCode" value="" />
            <input id="shevle_list_dName" name="dName" value="" />
            <input id="shevle_list_confusionMethod" name="confusionMethod" value="" />
            <input id="shevle_list_classify" name="classify" value="" />
        </form>
         <div class="query_box" id="shevle_list_yy" title="查询选项">
            <form id="shevle_list_queryForm" style="max-width:100%;">
			 <ul class="form-elements">
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_shevelNo" style="margin-right:20px;width:100%;">
						<span class="form_label" style="width:65px;">货架编号：</span>
						<input type="text" name="shevelNo" id="shevle_list_shevelNo" value="" style="width: calc(100% - 75px );" placeholder="货架编号">
					</label>			
				</li>
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_shevelName" style="margin-right:20px;width:100%;">
						<span class="form_label" style="width:65px;">货架名称：</span>
						<input type="text" name="shevelName" id="shevle_list_shevelName" value="" style="width: calc(100% - 75px );" placeholder="货架名称">
					</label>			
				</li>
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_confusionMethod" style="margin-right:20px;width:100%;">
						<span class="form_label" style="width:65px;">混放策略：</span>
						<input type="radio" id = "shevle_list_confusionMethod0" name="confusionMethod" value="0" checked> 是
					    <input type="radio" id = "shevle_list_confusionMethod1" name="confusionMethod" value="1"> 否
					</label>
					<label class="inline" for="shevle_list_classify" style="margin-right:20px;width:100%;">
						<span class="form_label" style="width:65px;">ABC分类：</span>
						<input type="radio" id = "shevle_list_classify0" name="classify" value="0" checked> A
					    <input type="radio" id = "shevle_list_classify1" name="classify" value="1"> B
					    <input type="radio" id = "shevle_list_classify2" name="classify" value="2"> C
					</label>			
				</li>	
			</ul>
			<div class="field-button">
				<div class="btn btn-info" onclick="queryOk();">
		            <i class="ace-icon fa fa-check bigger-110"></i>查询
	            </div>
				<div class="btn" onclick="reset();"><i class="ace-icon icon-remove"></i>重置</div>
	        </div>
		  </form>		 
    </div>        
         <div class="query_box" id="shevle_list_xx" title="查询选项">
            <form id="shevle_list_queryForms" style="max-width:100%;">
			 <ul class="form-elements">
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_shevelNo" style="margin-right:20px;">
						<span class="form_label" style="width:65px;">库位编号：</span>
						<input type="text" name="shevelNo" id="shevle_list_shevelNo" value="" style="width: 200px;" placeholder="库位编号">
					</label>			
				</li>
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_shevelName" style="margin-right:20px;">
						<span class="form_label" style="width:65px;">库位名称：</span>
						<input type="text" name="shevelName" id="shevle_list_shevelName" value="" style="width: 200px;" placeholder="库位名称">
					</label>			
				</li>
				<li class="field-group field-fluid3">
					<label class="inline" for="shevle_list_confusionMethod" style="margin-right:20px;">
						<span class="form_label" style="width:65px;">混放策略：</span>
						<input type="radio" id = "shevle_list_confusionMethod0" name="confusionMethod" value="0" checked> 是
					    <input type="radio" id = "shevle_list_confusionMethod1" name="confusionMethod" value="1"> 否
					</label>
					<label class="inline" for="shevle_list_classify" style="margin-right:20px;">
						<span class="form_label" style="width:65px;">ABC分类：</span>
						<input type="radio" id = "shevle_list_classify0" name="classify" value="0" checked> A
					    <input type="radio" id = "shevle_list_classify1" name="classify" value="1"> B
					    <input type="radio" id = "shevle_list_classify2" name="classify" value="2"> C
					</label>			
				</li>				
			</ul>
			<div class="field-button">
				<div class="btn btn-info" onclick="queryOk();">
		            <i class="ace-icon fa fa-check bigger-110"></i>查询
	            </div>
				<div class="btn" onclick="reset();"><i class="ace-icon icon-remove"></i>重置</div>
	        </div>
		  </form>		 
    </div>
        <div id="shevle_list_fixed_tool_div" class="fixed_tool_div">
            <div id="shevle_list___toolbar__" style="float:left;overflow:hidden;"></div>
        </div>
        <!--    货架信息表格 -->
        <table id="shevle_list_grid-table" style="width:100%;height:100%;"></table>
        <!-- 	表格分页栏 -->
        <div id="shevle_list_grid-pager"></div>
    </div>
</div>
<script type="text/javascript">
/* 获取中间件基本信息开始 */
var name=null;
var ip=null;
var port=null;
var interfaceAuthority = "";
$(function(){
    $(".toggle_tools").click();
});
$.ajax({
    type: "POST",
    url: context_path + "/wmsbind/getInterfaceAuthority?time="+new Date().getTime(),
    dataType: 'json',
    success: function (data) {
        interfaceAuthority=data.interfaceAuthority;
        console.log(interfaceAuthority);
    }
});

$.ajax({
    type: "POST",
    url: context_path + '/wmsbind/getIp',
    dataType: 'json',
    cache: false,
    success: function (data) {
        name = data.name;
        ip = data.ip;
        port = data.port;
        console.log(name+","+ip+","+port);
    }
});
/* 获取中间件基本信息结束 */
    //-----------------初始化树----------------------------
    
var zTree;   //树形对象
var selectTreeId = 0;   //存放选中的树节点id
//树的相关设置
var setting = {
    check: {
        enable: true	
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    edit: {
        enable: false,
        drag:{
        	isCopy:false,
        	isMove:false
        }
    },
    callback: {
		onClick: zTreeOnClick,
		onAsyncSuccess: zTreeOnAsyncSuccess
    },
	async: {
		enable: true,
		url:context_path+"/wmsshevle/allTreeData",
		autoParam:["id"],
        otherParam:{"parentId":function (){
            return selectTreeId;}},
		type: "POST"
	},//异步加载数据
};

/**
 * 获取树中选中节点的id
 * @returns {Number}
 */
function getSelectNodeId(){
	var nodes = zTree.getSelectedNodes();
	var deptid = 0;
	var selectNode = {id:null,atype:0};
	if(nodes.length>0 ){
		selectNode.id =  nodes[0].id;
		selectNode.atype = nodes[0].atype;
	}
	
	return selectNode;
}

//ztree加载成功之后的回调函数
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	zTree.expandAll(true);
	var datalist = JSON.parse(msg);
	//默认点击第一个
    if(datalist.length>0 && selectTreeId==0){
    	console.dir(datalist);
    	var clickNode = zTree.getNodeByParam("id", datalist[0].id, null);
    	clickNode.click = zTreeOnClick(null,null,clickNode);
    	zTree.selectNode(clickNode);
    }else{
    	$("#shevle_list_xx").attr("style","display:none");
    }
};

//树节点click事件
function zTreeOnClick(event, treeId, treeNode) {
	//节点点击事件 alert(treeNode.tId + ", " + treeNode.name);
	//后台获取相应工程的地图数据
	var selectnodes = zTree.getSelectedNodes();  //选中的节点
	selectTreeId = treeNode.id;   //记录每次点击的树节点
	console.log(treeNode.id+","+treeNode.atype+","+treeNode.name);
	var  s =  treeNode.id.split("-");  //节点ID
	if(treeNode.atype==0 || treeNode.atype==1){
		$("#shevle_list_yy").removeAttr("style","display:none");
		$("#shevle_list_xx").attr("style","display:none");
		$(".itbtn-grp:eq(2)").show();
	}
	if(treeNode.atype==2){
		$("#shevle_list_xx").removeAttr("style","display:none");
		$("#shevle_list_yy").attr("style","display:none");
		$(".itbtn-grp:eq(2)").hide();
	}
	reload_device(s[1],treeNode.atype,"");

};


//初始化树
$.fn.zTree.init($("#shevle_list_areaTreeDiv"), setting);
zTree = $.fn.zTree.getZTreeObj("shevle_list_areaTreeDiv");
    
    
    //----------------------------货架列表---------------------------------------------------
    var oriData;      //表格数据
    var _grid;        //表格对象
    //工具栏
    $("#shevle_list___toolbar__").iToolBar({
        id: "shevle_list___tb__01",
        items: [
            {label: "添加", disabled:(${sessionUser.addQx}==1?false:true),onclick:addShevel, iconClass:'icon-plus'},
    		{label: "编辑", disabled:(${sessionUser.editQx}==1?false:true),onclick:editShevel, iconClass:'icon-pencil'},
    		{label: "删除", disabled:(${sessionUser.deleteQx}==1?false:true),onclick:delShevel, iconClass:'icon-trash'},
			{label: "导出", disabled:(${sessionUser.queryQx}==1?false:true),onclick:excelShevel,iconClass:'icon-share'}
    ]
    });
var openWindowIndex = null;
var dynamicDefalutValue="5b945db3ab31420f8229f0759ab7eb8b";
function reload_device(id,typeId,queryJsonString){
    var colNames = '';
    var colModel = '';
    $.ajax({
        type: 'POST',
        url: context_path + "/wmsshevle/getGroupHeaders",
        data :{"typeId":typeId},
        success: function (data) {
        	colNames = data.colNames;
			colModel = data.colModel;
			//添加可视化操作字段
            colModel[7].formatter = confusionMethod;
            colModel[8].formatter = function(CellValue,options,RowObject){
                  if(CellValue==0){
                      return "是";
                  }
                  if(CellValue==1){
                      return "否";
                  }else{
                      return "";
                  }
              };
            colModel[9].formatter = function(CellValue,options,RowObject){
                  if(CellValue==0){
                     return "A";
                  }
                  if(CellValue==1){
                     return "B";
                  }
                  if(CellValue==2){
                     return "C";
                  }else{
                     return "";
                  }
            };
            jQuery('#shevle_list_grid-table').GridDestroy();
            $("#shevle_list_grid-div").append('<table id="grid-table" style="width:100%;height:100%;"></table>');
            $("#shevle_list_grid-div").append('<div id="grid-pager"></div>');
            _grid = jQuery("#shevle_list_grid-table").jqGrid({
            	type:'POST',
                url: context_path + data.url,
                datatype: "json",
                postData :{areaId:id,atype:typeId,queryJsonString:queryJsonString},
                colNames:colNames,
                colModel:colModel,
                rowNum: 20,
                rowList: [10, 20, 30],
                pager: '#shevle_list_grid-pager',
                sortname: 'type',
                sortorder: "desc",
                altRows: true,
                viewrecords: true,
                //caption: "设备列表",
                hidegrid: false,
                autowidth: true,
                multiselect: true,
                multiboxonly: true,
                beforeRequest:function (){
                    dynamicGetColumns(dynamicDefalutValue,"shevle_list_grid-table",$(window).width()-$("#sidebar").width() -7);
                    //重新加载列属性
                },
                loadComplete: function (data) {
                   var table = this;
                   setTimeout(function () { updatePagerIcons(table);enableTooltips(table);}, 0);
                   oriData = data;
                },
                emptyrecords: "没有相关记录",
                loadtext: "加载中...",
                pgtext: "页码 {0} / {1}页",
                recordtext: "显示 {0} - {1}共{2}条数据"
            });
            //在分页工具栏中添加按钮
            jQuery("#shevle_list_grid-table").navGrid('#shevle_list_grid-pager', {
                edit: false,
                add: false,
                del: false,
                search: false,
                refresh: false
            }).navButtonAdd('#shevle_list_grid-pager', {
                caption: "",
                buttonicon: "ace-icon fa fa-refresh green",
                onClickButton: function () {
                    $("#shevle_list_grid-table").jqGrid('setGridParam',
                        {
                            postData: {areaId:id,atype:typeId,queryJsonString: ""} //发送数据
                        }
                    ).trigger("reloadGrid");
                }
            }).navButtonAdd('#shevle_list_grid-pager',{
                caption: "",
                buttonicon:"fa  icon-cogs",
                onClickButton : function (){
                    jQuery("#shevle_list_grid-table").jqGrid('columnChooser',{
                        done: function(perm, cols){
                            dynamicColumns(cols,dynamicDefalutValue);
                            $("#shevle_list_grid-table").jqGrid( 'setGridWidth', $("#shevle_list_grid-div").width()-3);
                        }
                    });
                }
            });
            $(window).on('resize.jqGrid', function () {
                $("#shevle_list_grid-table").jqGrid("setGridWidth", $("#shevle_list_grid-div").width() - 3);
                $("#shevle_list_grid-table").jqGrid("setGridHeight",  $(".container-fluid").height()-
                $("#shevle_list_yy").outerHeight(true)-$("#shevle_list_fixed_tool_div").outerHeight(true)-
                $("#shevle_list_grid-pager").outerHeight(true)-$("#gview_shevle_list_grid-table .ui-jqgrid-hdiv").outerHeight(true));
            });
            $(window).triggerHandler('resize.jqGrid');
        },
        dataType: "json"
    });
}
    var _queryForm_data = iTsai.form.serialize($('#shevle_list_queryForm'));
    
	function queryOk(){
		var queryParam = "";
		if(getSelectNodeId().atype==0 || getSelectNodeId().atype==1){
			queryParam = iTsai.form.serialize($('#shevle_list_queryForm'));
		}else{
			queryParam = iTsai.form.serialize($('#shevle_list_queryForms'));
		}
		console.dir(queryParam);
		//执行父窗口中的js方法：将当前窗口中的form的值传递到父窗口，并放到父窗口中隐藏的form中，接着执行刷新父窗口列表的操作
		queryAreaListByParam(queryParam);
		
	}
	
	function reset(){
        if(getSelectNodeId().atype==0 || getSelectNodeId().atype==1){
            iTsai.form.deserialize($('#shevle_list_queryForm'),_queryForm_data);
        }else{
            iTsai.form.deserialize($('#shevle_list_queryForms'),_queryForm_data);
        }
		//执行父窗口中的js方法：将当前窗口中的form的值传递到父窗口，并放到父窗口中隐藏的form中，接着执行刷新父窗口列表的操作
		queryAreaListByParam(_queryForm_data);
		
	}

	function confusionMethod(CellValue,options,RowObject){
        if(CellValue==0) return "是";
        else if(CellValue==1) return "否";
        else return "";
    }
	
    function locked(CellValue,options,RowObject){
        if(CellValue==0) return "是";
        else if(CellValue==1) return "否";
        else return "";
    }
    
    function classify(CellValue,options,RowObject){
        if(CellValue==0) return "A";
        else if(CellValue==1) return "B";
        else if(CellValue==2) return "C";
        else return "";
    }

/*货架导出*/
function excelShevel(){
    var selectid = getId("#shevle_list_grid-table","id");
    $("#shevle_list_ids").val(selectid);
    $("#shevle_list_hiddenForm").submit();
}
	
	/**
	 * 入库单查询功能:获取查询页面中的值，并将值放入列表页面中隐藏的form
	 * @param jsonParam     查询页面传递过来的json对象
	 */
	function queryAreaListByParam(jsonParam) {
	    //序列化表单：iTsai.form.serialize($('#frm'))
	    //反序列化表单：iTsai.form.deserialize($('#frm'),json)
	    iTsai.form.deserialize($('#shevle_list_hiddenQueryForm'), jsonParam);   //将json对象反序列化到列表页面中隐藏的form中
	    var queryParam = iTsai.form.serialize($('#shevle_list_hiddenQueryForm'));
	    var queryJsonString = JSON.stringify(queryParam);         //将json对象转换成json字符串
	    
	    //执行查询操作
	    var selecttreeData = getSelectNodeId();
	    var ids = selecttreeData.id.split("-")[1];
	    reload_device(ids,getSelectNodeId().atype,queryJsonString);

	}
	
	/**
	 * 新增货架
	 */
	function addShevel() {
		 var selecttreeData = getSelectNodeId();
		 var id = selecttreeData.id.split("-")[1];
		 if(id){
			 if(selecttreeData.atype==1){//选择库区可以添加货架
				//打开新增界面
			    $.get(context_path + "/wmsshevle/addShevel.do?id="+'-1'+'&area_id='+id).done(function(data){
			    	openWindowIndex = layer.open({
		    		    title : "货架添加",
		    	    	type:1,
		    	    	skin : "layui-layer-molv",
		    	    	area : "600px",
		    	    	shade : 0.6, //遮罩透明度
		    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
		    		    anim : 2,
		    		    content : data
		    		});
		        });
			 }if(selecttreeData.atype==2){				//库位的添加
				//打开新增界面
				$.get(context_path+'/wmsbind/toMainBinds?id='+'-1'+'&stuff_id='+id).done(function(data){
			    	openWindowIndex = layer.open({
		    		    title : "库位添加 ",
		    	    	type:1,
		    	    	skin : "layui-layer-molv",
		    	    	area : "600px",
		    	    	shade : 0.6, //遮罩透明度
		    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
		    		    anim : 2,
		    		    content : data
		    		});
		        });
			 }
			 if(selecttreeData.atype==0){
				 layer.alert("仓库不可添加货架,要选择一个库区进行货架的添加！");
			 }
		 }

	}

	/**
	 * 修改区域
	 */
	function editShevel() {
	    var checkedNum = getGridCheckedNum("#shevle_list_grid-table", "id");
	    if (checkedNum == 0) {
	    	layer.alert("请选择一个要编辑的货架！");
	        return false;
	    } else if (checkedNum > 1) {
	    	layer.alert("只能选择一个货架进行编辑操作！");
	        return false;
	    } else {
	        var areaId = jQuery("#shevle_list_grid-table").jqGrid('getGridParam', 'selrow');
	        var selecttreeData = getSelectNodeId();
	        var ids = selecttreeData.id.split("-")[1];
	        if(selecttreeData.atype==1){
		        $.get(context_path + "/wmsshevle/addShevel.do?id=" + areaId+"&area_id=" + ids).done(function(data){
		        	openWindowIndex = layer.open({
		    		    title : "货架编辑", 
		    	    	type:1,
		    	    	skin : "layui-layer-molv",
		    	    	area : "600px",
		    	    	shade : 0.6, //遮罩透明度
		    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
		    		    anim : 2,
		    		    content : data
		    		});
		        });
	        }
	        if(selecttreeData.atype==2){
	        	$.get(context_path+'/wmsbind/toMainBinds?id='+areaId+'&stuff_id='+ids).done(function(data){
					openWindowIndex = layer.open({
	    		    title : "编辑库位", 
	    	    	type:1,
	    	    	skin : "layui-layer-molv",
	    	    	area : "600px",
	    	    	shade : 0.6, //遮罩透明度
	    		    moveType : 1, //拖拽风格，0是默认，1是传统拖动
	    		    anim : 2,
	    		    content : data,
    		});
        });
	        }
	    }
        if(selecttreeData.atype==0){
            layer.alert("仓库不可编辑货架,要选择一个库区进行货架的编辑！");
        }
	}
	
	/**
	 * 重新加载列表数据
	 * @param parentTreeId
	 */
	function reloadGridDatas() {
		var areaId = getSelectNodeId().id.split("-");
		var s = areaId[1];
		reload_device(s,getSelectNodeId().atype,"");
	}
	
	/**
	 * 显示提示窗口
	 * @param msg   显示信息
	 * @param delay 持续时间,结束之后窗口消失
	 */
	function showTipMsg(msg, delay) {
	    Dialog.tip(msg, {type: "loading", delay: delay});
	}

	function getId(_grid,_key){
	    var idAddr = jQuery(_grid).getGridParam("selarrrow");
	    var ids="";
	    ids=idAddr.join(",");
	    return ids;
	}
	/**
	 *删除货架
	 */
	function delShevel() {
	    var checkedNum = getGridCheckedNum("#shevle_list_grid-table", "id");  //选中的数量
	    var ids = getId("#shevle_list_grid-table","id");   //获取选中行的id
		
	    if (checkedNum == 0) {
	    	layer.alert("请选择一个要删除的货架！");
	    } else {
	    	var selecttreeData = getSelectNodeId();
	        //弹出确认窗口
	        if(selecttreeData.atype==1){		//选择库区可以添加货架
	        layer.confirm('确定删除选中的货架？',
	                function () {
			        	$.ajax({
		                    type: "POST",
		                    url: context_path + "/wmsshevle/deleteShevel.do?ids=" + ids+"&name="+name+"&ip="+ip+"&port="+port,
		                    dataType: "json",
		                    success: function (result) {
		                        if (result.result) {
		                            var node = zTree.getSelectedNodes()[0];
		                            selectTreeId  =  node.id;
		      			         	zTree.reAsyncChildNodes(node, "refresh",false);
		                            layer.msg("货架删除成功！");
		                            reloadGridDatas();//重新加载表格
		                        } else {
		                            if (result.msg != "删除失败!") layer.alert(result.msg);
		                            else layer.alert("删除失败！");
		                        }
		                    }
		                });
	                }
	            );
	            }
	            if(selecttreeData.atype==2){				//删除库位中的信息				
	            	layer.confirm('确定删除选中的库位？', /*显示的内容*/
				{
				  shift: 6,
				  moveType: 1, //拖拽风格，0是默认，1是传统拖动
				  title:"操作提示",  /*弹出框标题*/
				  icon: 3,      /*消息内容前面添加图标*/
				  btn: ['确定', '取消']/*可以有多个按钮*/
				}, function(index, layero){
					$.ajax({
						url:context_path + "/wmsbind/deleteGoods",
						type:"POST",
						data:{ids : ids},
						dataType:"json",
						success:function(data){
							if(data){
								layer.msg("操作成功!",{icon:1});
								//刷新用户列表
								reloadGridDatas();
								layer.close(index);
							}else{
								layer.msg("操作失败!",{icon:2});
							}
					   }
					});
					
				}, function(index){
				  //取消按钮的回调
				  layer.close(index);
				});
				}
		}
	}
	
	function openVisual(id){
		localStorage.clear();//清除浏览器缓存
		var windowH = $(window).height();
		var windowW = $(window).width();
		layer.open({
			  type: 2,
			  title: '货架可视化',
			  shadeClose: true,
			  shade: false,
			  maxmin: false, //开启最大化最小化按钮
			  area: [windowW+'px', windowH+'px'],
			  content: context_path+"/wmsbind/toVisual?id="+id
		});
	}
	
	function format(cv,options,row){
		editBtn = "<div id='"+row.id+"' class='btn btn-xs btn-success' onclick='openVisual(this.id)' >可视化</div>";
		return editBtn
	}
	
</script>

